package org.jsbd.boss.timer;

import org.jsbd.boss.common.redis.RedisClient;
import org.jsbd.boss.service.impl.CacheParamManager;
import org.jsbd.boss.util.PropertiesUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import javax.annotation.PostConstruct;
import javax.annotation.Resource;

public abstract class BaseTaskTimer {
    final private static Logger logger = LoggerFactory.getLogger(BaseTaskTimer.class);

    @Resource
    protected CacheParamManager cacheParamManager;

    @Resource
    protected RedisClient<String, Object> redisClient;

    protected int expireTime = 60;

    private String taskFlag = PropertiesUtil.getValue("task_flag", "off");


//    @PostConstruct
    private void init() {
        new Thread(new Runnable() {
            @Override
            public void run() {
                try {
                    Thread.sleep(30000);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                if ("on".equalsIgnoreCase(taskFlag)) {
                    while (true) {
                        try {
                            Thread.sleep(initSleepTime() * 1000);
                            if (isCanDo()) {
                                execute();
                            }
                        } catch (Exception e) {
                            logger.error("BaseTaskTimer error", e);
                        }
                    }
                }
            }
        }).start();

    }

    /**
     * isCanDo:TODO 请描述该方法是做什么用途的
     *
     * @return
     * @author <a href="mailto:xupengcheng@zhexinit.com" >徐鹏程</a>
     */
    protected boolean isCanDo() {
        return true;
    }

    /**
     * execute:任务执行
     *
     * @author <a href="mailto:xupengcheng@zhexinit.com" >徐鹏程</a>
     */

    abstract void execute();

    /**
     * initSleepTime:单位 秒 默认一分钟
     *
     * @return
     * @author <a href="mailto:xupengcheng@zhexinit.com" >徐鹏程</a>
     */
    protected int initSleepTime() {
        return 3;
    }

}
